//
//  YWPosterPuzzleController.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/8/29.
//

#import "YWPosterPuzzleController.h"
#import "YWPuzzleStatus.h"
#import "YWPosterPuzzleLayout1.h"
#import "YWPosterPuzzleLayout2.h"
#import "YWPosterPuzzleLayout3.h"
#import "YWPosterPuzzleLayout4.h"
#import "YWTemplatePuzzleCell.h"

@interface YWPosterPuzzleController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate>

@property(nonatomic,strong)UICollectionView *collectionView;

@property(nonatomic,strong)NSMutableArray *puzzleArray;

- (IBAction)puzzleBtnClick1:(UIButton *)sender;

- (IBAction)puzzleBtnClick2:(UIButton *)sender;

- (IBAction)puzzleBtnClick3:(UIButton *)sender;

- (IBAction)puzzleBtnClick4:(UIButton *)sender;


@property(nonatomic,weak)UIImageView *imageView;

@property (weak, nonatomic) IBOutlet UIView *bgView;

// - - -

//这里手势用强引用
@property(nonatomic,strong)UIPanGestureRecognizer *panRecognizer;

@property(nonatomic,strong)UIPinchGestureRecognizer *pinchRecognizer;

// - - -

@property(nonatomic,weak)YWTemplatePuzzleCell *handleThisCell;//处理的是这个cell（无论缩放还是移动）、相当于华人的lastPassCell

@property(nonatomic,strong)UIImageView *panImageView;

@property(nonatomic,strong)NSIndexPath *beginIndexPath;
@property(nonatomic,strong)NSIndexPath *endIndexPath;

//@property(nonatomic,assign)NSInteger lastItem;

@property(nonatomic,assign)BOOL isMovingCellToOutSide;

// - - -

@end

@implementation YWPosterPuzzleController

static NSString * const cellID = @"YWTemplatePuzzleCell";


-(UIImageView *)panImageView{
    if(_panImageView == nil){
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self.collectionView addSubview:imageView];
        imageView.layer.cornerRadius = 5;
        imageView.clipsToBounds = YES;
        imageView.hidden = YES;
        _panImageView = imageView;
        
    }
    return _panImageView;
}


- (IBAction)puzzleBtnClick2:(UIButton *)sender {
    
    [self.collectionView setCollectionViewLayout:[[YWPosterPuzzleLayout2 alloc]init] animated:YES];
    
    //重置frame
    NSArray *cellArray = [self.collectionView visibleCells];
    for (YWTemplatePuzzleCell *cell in cellArray) {
        [cell reloadFrame];
    }
    
    self.imageView.image = [UIImage imageNamed:@"b22"];
}

- (IBAction)puzzleBtnClick1:(UIButton *)sender {
    
    [self.collectionView setCollectionViewLayout:[[YWPosterPuzzleLayout1 alloc]init] animated:YES];
    
    //重置frame
    NSArray *cellArray = [self.collectionView visibleCells];
    for (YWTemplatePuzzleCell *cell in cellArray) {
        [cell reloadFrame];
    }
    
    self.imageView.image = [UIImage imageNamed:@"a11"];
}



- (IBAction)puzzleBtnClick3:(UIButton *)sender{
    [self.collectionView setCollectionViewLayout:[[YWPosterPuzzleLayout3 alloc]init] animated:YES];
    
    //重置frame
    NSArray *cellArray = [self.collectionView visibleCells];
    for (YWTemplatePuzzleCell *cell in cellArray) {
        [cell reloadFrame];
    }
    
    
    self.imageView.image = [UIImage imageNamed:@"c33"];
}

- (IBAction)puzzleBtnClick4:(UIButton *)sender{
    [self.collectionView setCollectionViewLayout:[[YWPosterPuzzleLayout4 alloc]init] animated:YES];
    
    //重置frame
    NSArray *cellArray = [self.collectionView visibleCells];
    for (YWTemplatePuzzleCell *cell in cellArray) {
        [cell reloadFrame];
    }
    
    self.imageView.image = [UIImage imageNamed:@"d44"];
    
}






-(NSMutableArray *)puzzleArray{
    if(_puzzleArray == nil){
        _puzzleArray = [NSMutableArray array];
    }
    return _puzzleArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"YWFreedomPuzzleController:%ld",self.photos.count);
    NSLog(@"YWFreedomPuzzleController:%ld",self.assets.count);
    
    NSMutableArray *mArray = [NSMutableArray array];
    for (UIImage *image in self.photos) {
        YWPuzzleStatus *status = [[YWPuzzleStatus alloc] init];
        status.image = image;
        [mArray addObject:status];
    }
    self.puzzleArray = mArray;
    
    self.bgView.clipsToBounds = YES;
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"a11"];
    [self.bgView addSubview:imageView];
    self.imageView = imageView;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[YWPosterPuzzleLayout1 alloc]init]];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [self.bgView addSubview:collectionView];
    
    [collectionView registerNib:[UINib nibWithNibName:@"YWTemplatePuzzleCell" bundle:nil] forCellWithReuseIdentifier:cellID];
    
    collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView = collectionView;
    
    
    //添加手势
    // pan
    // 拖拽手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]
                                   initWithTarget:self action:@selector(pan:)];
    
    [collectionView addGestureRecognizer:pan];
    self.panRecognizer = pan;
    
    // pinch
    // 捏合
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
    
    pinch.delegate = self;
    [collectionView addGestureRecognizer:pinch];
    self.pinchRecognizer = pinch;
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSArray *cellArray = [self.collectionView visibleCells];
    for (UICollectionViewCell *cell in cellArray) {
        cell.layer.borderColor = [UIColor whiteColor].CGColor;
        cell.layer.borderWidth = 5;
    }
}


//捏合的时候调用.
- (void)pinch:(UIPinchGestureRecognizer *)pinch
{
    
    //判断手势状态
    switch (pinch.state) {
            
            //一开始拖拽
        case UIGestureRecognizerStateBegan:{
            
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[pinch locationInView:self.collectionView]];
            
            //假如不是在indexPath范围内的，直接返回
            if (indexPath == nil) {
                break;
            }
            
            
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
            
             if ([cell isKindOfClass:[YWTemplatePuzzleCell class]]){
                 YWTemplatePuzzleCell *puzzleCell = (YWTemplatePuzzleCell *)cell;
                 self.handleThisCell = puzzleCell;
            }
            
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            if (self.handleThisCell == nil) {
                break;
            }
            
            self.handleThisCell.scaleInscrease = pinch.scale;
            
        }
            break;
        case UIGestureRecognizerStateEnded:{
            
            self.handleThisCell = nil;
            
        }
            
            break;
        default:
            
            break;
    }
    
    
    
    // 复位
    pinch.scale = 1;
}


//拖动的时候调用
- (void)pan:(UIPanGestureRecognizer *)pan{
    
    //判断手势状态
    switch (pan.state) {
            
            //一开始拖拽
        case UIGestureRecognizerStateBegan:{
            
            self.isMovingCellToOutSide = NO;
            
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[pan locationInView:self.collectionView]];
            
            //假如不是在indexPath范围内的，直接返回
            if (indexPath == nil) {
                break;
            }
            
            
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
            
             if ([cell isKindOfClass:[YWTemplatePuzzleCell class]]){
                 YWTemplatePuzzleCell *puzzleCell = (YWTemplatePuzzleCell *)cell;
                 self.handleThisCell = puzzleCell;
            }
            
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            if (self.handleThisCell == nil) {
                break;
            }
            
            //所有cell置为无框
            NSArray *cellArray = [self.collectionView visibleCells];
            for (UICollectionViewCell *cell in cellArray) {
                cell.layer.borderColor = [UIColor whiteColor].CGColor;
            }
            
            CGPoint point = [pan locationInView:self.collectionView];
            
            if (CGRectContainsPoint(self.handleThisCell.frame, point)) { //手指在cell里面移动
                
                if(self.isMovingCellToOutSide == YES){ //假如从外面回来一开始处理的cell里面了
                    
                  CGPoint handleThisCellPoint = [self.collectionView convertPoint:point toView:self.handleThisCell];
                    
                    self.handleThisCell.panCenter = handleThisCellPoint; //图片的中间放在手指位置
                    
                }
                
                
                CGPoint transP = [pan translationInView:pan.view];
                
                self.handleThisCell.panXInscrease = transP.x;
                self.handleThisCell.panYInscrease = transP.y;
                
                
                self.handleThisCell.imageView.hidden = NO;
                self.panImageView.hidden = YES;
                
                self.isMovingCellToOutSide = NO;
                self.endIndexPath = nil;
                
            }
            else{ //手指离开了在cell在外面移动
                
                if(self.isMovingCellToOutSide == NO){ //第一次移动到外面
                    
                    self.isMovingCellToOutSide = YES;
                    
                    NSIndexPath *indexPath = [self.collectionView indexPathForCell:self.handleThisCell];
                    
                    self.beginIndexPath = indexPath;
                    
                    self.handleThisCell.imageView.hidden = YES;
                    self.panImageView.hidden = NO;
                    
                    self.panImageView.image = self.handleThisCell.status.image;
                    
                    
                    self.panImageView.center = [pan locationInView:self.collectionView];
                    CGSize imageSize = self.handleThisCell.status.image.size;
                    if(imageSize.width >= imageSize.height){
                        self.panImageView.bounds = CGRectMake(0, 0, (Wi-40)/3 + 30, (Wi-40)/3 - 30);
                    }else{
                        self.panImageView.bounds = CGRectMake(0, 0, (Wi-40)/3 - 30, (Wi-40)/3 + 30);
                    }
                    
                }
                else{ //第二次change之后还是在外面
                    
                    //图片跟随手指移动
                    self.panImageView.center = [pan locationInView:self.collectionView];
                    
                    //手指去到哪个cell就哪个cell有框
                    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[pan locationInView:self.collectionView]];
                    
                    self.endIndexPath = indexPath; //假如不是在cell里面，indexPath就是nil
                    
                    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
                    
                    if ([cell isKindOfClass:[YWTemplatePuzzleCell class]]) { //去到其它cell
                        
                        cell.layer.borderColor = [UIColor systemPinkColor].CGColor;
//                        cell.layer.borderWidth = 5;
                                           
                    }
                    
                    
                }
                
            }
            
        }
            break;
        case UIGestureRecognizerStateEnded:{
            
            //所有cell置为无框
            NSArray *cellArray = [self.collectionView visibleCells];
            for (UICollectionViewCell *cell in cellArray) {
                cell.layer.borderColor = [UIColor whiteColor].CGColor;
            }
            
            
            //考虑的是3种情况
            
            if(self.isMovingCellToOutSide == NO){  //情况一：一直都在自己cell上移动 / 在别人cell移动后再回来自己cell上移动 / self.handleThisCell == nil的时候也可以对应走这里
                
                //这里保持原状不需要理
                
                
            }
            else if(self.endIndexPath == nil){ //情况二：去了外面但不在cell上移动
                
                
                [self.handleThisCell reloadFrame];
                
            }
            else{ //情况三：在别人cell上移动
                
                
                //两个数组都要改变模型
                NSMutableArray *mArray = [NSMutableArray arrayWithArray:self.puzzleArray];

                YWPuzzleStatus *imageStatus = mArray[self.beginIndexPath.item];

                [mArray removeObject:imageStatus];

                [mArray insertObject:imageStatus atIndex:self.endIndexPath.item];

                self.puzzleArray = mArray;

                //样式
                [self.collectionView moveItemAtIndexPath:self.beginIndexPath toIndexPath:self.endIndexPath];
                
                
                //要刷新cell的frame
                [self.handleThisCell reloadFrame];
                
                YWTemplatePuzzleCell *endCell = (YWTemplatePuzzleCell *)[self.collectionView cellForItemAtIndexPath:self.endIndexPath];
                
                [endCell reloadFrame];
                
            }
            
            self.isMovingCellToOutSide = NO;
            
            self.handleThisCell.imageView.hidden = NO;
            self.panImageView.hidden = YES;
            
            self.handleThisCell = nil;
            
            self.beginIndexPath = nil;
            self.endIndexPath = nil;
            
            
        }
            
            break;
        default:
            
            break;
    }
    
    
    //复位
    [pan setTranslation:CGPointZero inView:pan.view];
    
}


//能够同时支持多个手势
-(BOOL)gestureRecognizer:(nonnull UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(nonnull UIGestureRecognizer *)otherGestureRecognizer{
    
    return YES;
}


-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.collectionView.frame = self.bgView.bounds;
    self.imageView.frame = self.bgView.bounds;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.puzzleArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YWPuzzleStatus *status = self.puzzleArray[indexPath.item];
    
    YWTemplatePuzzleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    cell.status = status;
    
    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;
    
}

-(UIImage *)getCurrentLayer{
    
    //1.开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(self.bgView.size, NO, 0);
    
    //2.把画板上的内容渲染到上下文当中
    CGContextRef ctx =  UIGraphicsGetCurrentContext();
    [self.bgView.layer renderInContext:ctx];
    
    //3.从上下文当中取出一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //4.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}


@end
